package design.pattern.Lu22FlyweightPattern;

import java.util.HashMap;
import java.util.Map;

/**
 * @program JavaBase
 * @description: 享元模式
 * @author: zhanglu
 * @create: 2020-05-19 20:39:00
 */
public class FlyweightPattern01 {

    public static void main(String[] args) {

    }

}

abstract class Flyweight{
    //内部状态
    private String intrinsic;
    //外部状态
    protected final String extrinsic;
    //要求享元角色必须接受外部状态
    public Flyweight(String extrinsic) {
        this.extrinsic = extrinsic;
    }
    //定义业务操作
    public abstract void operate();

    public String getIntrinsic(){
        return intrinsic;
    }

    public void setIntrinsic(String intrinsic){
        this.intrinsic = intrinsic;
    }
}

class ConcreteFlyweight01 extends Flyweight{

    public ConcreteFlyweight01(String extrinsic) {
        super(extrinsic);
    }

    @Override
    public void operate() {

    }
}

class FlyweightFactory{
    private static Map<String, Flyweight> pool = new HashMap<>();

    public static Flyweight getFlyweight(String extrinsic){
        Flyweight flyweight = null;
        if(pool.containsKey(extrinsic)){
            flyweight = pool.get(extrinsic);
        }else {
            flyweight = new ConcreteFlyweight01(extrinsic);
            pool.put(extrinsic, flyweight);
        }
        return flyweight;
    }
}


